package oa.hleast.common.upload.component;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.IdUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.*;
import oa.hleast.common.upload.config.UploadProperties;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;

import java.io.InputStream;

@Slf4j
@ConditionalOnProperty(prefix = "upload",value = {"provider"},havingValue = "ali-oss")
@EnableConfigurationProperties({UploadProperties.class})
public class AliOssService implements InitializingBean, IFileService {

    private UploadProperties uploadProperties;

    public AliOssService(UploadProperties UploadProperties) {
        this.uploadProperties = UploadProperties;
    }

    private OSS client;

    @Override
    public void afterPropertiesSet() {
        Assert.notBlank(uploadProperties.getEndpoint(), "URL 为空");
        Assert.notBlank(uploadProperties.getAccessKey(), "accessKey为空");
        Assert.notBlank(uploadProperties.getSecretKey(), "secretKey为空");
        this.client = new OSSClientBuilder().build(uploadProperties.getEndpoint(), uploadProperties.getAccessKey(), uploadProperties.getSecretKey());
    }

    @SneakyThrows
    public void createBucketIfAbsent(String bucketName) {
        if (!client.doesBucketExist(bucketName)) {
            CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName);
            createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
            Bucket bucket = client.createBucket(createBucketRequest);
            if (bucket != null) System.out.println(bucket.getName());
        }
    }

    public String uploadFile(InputStream file, String ext, String bucketName) throws Exception {
        String objectName = IdUtil.simpleUUID() + "." + ext;
        return putObject(bucketName, objectName, file);
    }

    @Override
    public String putObject(String bucketName, String objectName, InputStream inputStream) throws Exception {
        createBucketIfAbsent(bucketName);
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, inputStream);

        ObjectMetadata metadata = new ObjectMetadata();
// metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
        metadata.setObjectAcl(CannedAccessControlList.PublicRead);

        putObjectRequest.setMetadata(metadata);
        client.putObject(putObjectRequest);
        return uploadProperties.getShareUrl() + objectName;
    }

    @Override
    public void removeObject(String bucketName, String objectName) throws Exception {
        client.deleteObject(bucketName, objectName);
    }

}
